// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <tests/substrait/json_to_proto_converter.h>

#include <pollux/testing/gtest_utils.h>
#include <pollux/testing/dwio/data_files.h>
#include <pollux/testing/exec/util/assert_query_builder.h>
#include <pollux/testing/exec/util/hive_connector_test_base.h>
#include <pollux/plan/plan_builder.h>
#include <pollux/common/file/temp_directory_path.h>
#include <pollux/substrait/substrait_to_pollux_plan.h>
#include <pollux/type/type.h>

using namespace kumo::pollux;
using namespace kumo::pollux::test;
using namespace kumo::pollux::connector::hive;
using namespace kumo::pollux::exec;

class Substrait2PolluxPlanConversionTest
        : public exec::test::HiveConnectorTestBase {
protected:
    static void SetUpTestCase() {
        memory::MemoryManager::testingSetInstance({});
    }

    std::vector<std::shared_ptr<kumo::pollux::connector::ConnectorSplit> >
    makeSplits(
        const kumo::pollux::substrait::SubstraitPolluxPlanConverter &converter,
        std::shared_ptr<const core::PlanNode> planNode) {
        const auto &splitInfos = converter.splitInfos();
        auto leafPlanNodeIds = planNode->leafPlanNodeIds();
        // Only one leaf node is expected here.
        EXPECT_EQ(1, leafPlanNodeIds.size());
        const auto &splitInfo = splitInfos.at(*leafPlanNodeIds.begin());

        const auto &paths = splitInfo->paths;
        const auto &starts = splitInfo->starts;
        const auto &lengths = splitInfo->lengths;
        const auto fileFormat = splitInfo->format;

        std::vector<std::shared_ptr<kumo::pollux::connector::ConnectorSplit> >
                splits;
        splits.reserve(paths.size());

        for (int i = 0; i < paths.size(); i++) {
            auto path = fmt::format("{}{}", tmpDir_->getPath(), paths[i]);
            auto start = starts[i];
            auto length = lengths[i];
            auto split = kumo::pollux::exec::test::HiveConnectorSplitBuilder(path)
                    .fileFormat(fileFormat)
                    .start(start)
                    .length(length)
                    .build();
            splits.emplace_back(split);
        }
        return splits;
    }

    std::shared_ptr<exec::test::TempDirectoryPath> tmpDir_{
        exec::test::TempDirectoryPath::create()
    };
};

// This test will firstly generate mock TPC-H lineitem ORC file. Then, Pollux's
// computing will be tested based on the generated ORC file.
// Input: Json file of the Substrait plan for the below modified TPC-H Q6 query:
//
//  SELECT sum(l_extendedprice * l_discount) AS revenue
//  FROM lineitem
//  WHERE
//    l_shipdate_new >= 8766 AND l_shipdate_new < 9131 AND
//    l_discount BETWEEN .06 - 0.01 AND .06 + 0.01 AND
//    l_quantity < 24
//
//  Tested Pollux operators: TableScan (Filter Pushdown), Project, Aggregate.
TEST_F(Substrait2PolluxPlanConversionTest, DISABLED_q6) {
    // Generate the used ORC file.
    auto type =
            ROW({
                    "l_orderkey",
                    "l_partkey",
                    "l_suppkey",
                    "l_linenumber",
                    "l_quantity",
                    "l_extendedprice",
                    "l_discount",
                    "l_tax",
                    "l_returnflag",
                    "l_linestatus",
                    "l_shipdate",
                    "l_commitdate",
                    "l_receiptdate",
                    "l_shipinstruct",
                    "l_shipmode",
                    "l_comment"
                },
                {
                    BIGINT(),
                    BIGINT(),
                    BIGINT(),
                    INTEGER(),
                    DOUBLE(),
                    DOUBLE(),
                    DOUBLE(),
                    DOUBLE(),
                    VARCHAR(),
                    VARCHAR(),
                    DOUBLE(),
                    DOUBLE(),
                    DOUBLE(),
                    VARCHAR(),
                    VARCHAR(),
                    VARCHAR()
                });
    std::shared_ptr<memory::MemoryPool> pool{
        memory::memoryManager()->addLeafPool()
    };
    std::vector<VectorPtr> vectors;
    // TPC-H lineitem table has 16 columns.
    int colNum = 16;
    vectors.reserve(colNum);
    std::vector<int64_t> lOrderkeyData = {
        4636438147,
        2012485446,
        1635327427,
        8374290148,
        2972204230,
        8001568994,
        989963396,
        2142695974,
        6354246853,
        4141748419
    };
    vectors.emplace_back(make_flat_vector<int64_t>(lOrderkeyData));
    std::vector<int64_t> lPartkeyData = {
        263222018,
        255918298,
        143549509,
        96877642,
        201976875,
        196938305,
        100260625,
        273511608,
        112999357,
        299103530
    };
    vectors.emplace_back(make_flat_vector<int64_t>(lPartkeyData));
    std::vector<int64_t> lSuppkeyData = {
        2102019,
        13998315,
        12989528,
        4717643,
        9976902,
        12618306,
        11940632,
        871626,
        1639379,
        3423588
    };
    vectors.emplace_back(make_flat_vector<int64_t>(lSuppkeyData));
    std::vector<int32_t> lLinenumberData = {4, 6, 1, 5, 1, 2, 1, 5, 2, 6};
    vectors.emplace_back(make_flat_vector<int32_t>(lLinenumberData));
    std::vector<double> lQuantityData = {
        6.0, 1.0, 19.0, 4.0, 6.0, 12.0, 23.0, 11.0, 16.0, 19.0
    };
    vectors.emplace_back(make_flat_vector<double>(lQuantityData));
    std::vector<double> lExtendedpriceData = {
        30586.05,
        7821.0,
        1551.33,
        30681.2,
        1941.78,
        66673.0,
        6322.44,
        41754.18,
        8704.26,
        63780.36
    };
    vectors.emplace_back(make_flat_vector<double>(lExtendedpriceData));
    std::vector<double> lDiscountData = {
        0.05, 0.06, 0.01, 0.07, 0.05, 0.06, 0.07, 0.05, 0.06, 0.07
    };
    vectors.emplace_back(make_flat_vector<double>(lDiscountData));
    std::vector<double> lTaxData = {
        0.02, 0.03, 0.01, 0.0, 0.01, 0.01, 0.03, 0.07, 0.01, 0.04
    };
    vectors.emplace_back(make_flat_vector<double>(lTaxData));
    std::vector<std::string> lReturnflagData = {
        "N", "A", "A", "R", "A", "N", "A", "A", "N", "R"
    };
    vectors.emplace_back(make_flat_vector<std::string>(lReturnflagData));
    std::vector<std::string> lLinestatusData = {
        "O", "F", "F", "F", "F", "O", "F", "F", "O", "F"
    };
    vectors.emplace_back(make_flat_vector<std::string>(lLinestatusData));
    std::vector<double> lShipdateNewData = {
        8953.666666666666,
        8773.666666666666,
        9034.666666666666,
        8558.666666666666,
        9072.666666666666,
        8864.666666666666,
        9004.666666666666,
        8778.666666666666,
        9013.666666666666,
        8832.666666666666
    };
    vectors.emplace_back(make_flat_vector<double>(lShipdateNewData));
    std::vector<double> lCommitdateNewData = {
        10447.666666666666,
        8953.666666666666,
        8325.666666666666,
        8527.666666666666,
        8438.666666666666,
        10049.666666666666,
        9036.666666666666,
        8666.666666666666,
        9519.666666666666,
        9138.666666666666
    };
    vectors.emplace_back(make_flat_vector<double>(lCommitdateNewData));
    std::vector<double> lReceiptdateNewData = {
        10456.666666666666,
        8979.666666666666,
        8299.666666666666,
        8474.666666666666,
        8525.666666666666,
        9996.666666666666,
        9103.666666666666,
        8726.666666666666,
        9593.666666666666,
        9178.666666666666
    };
    vectors.emplace_back(make_flat_vector<double>(lReceiptdateNewData));
    std::vector<std::string> lShipinstructData = {
        "COLLECT COD",
        "NONE",
        "TAKE BACK RETURN",
        "NONE",
        "TAKE BACK RETURN",
        "NONE",
        "DELIVER IN PERSON",
        "DELIVER IN PERSON",
        "TAKE BACK RETURN",
        "NONE"
    };
    vectors.emplace_back(make_flat_vector<std::string>(lShipinstructData));
    std::vector<std::string> lShipmodeData = {
        "FOB",
        "REG AIR",
        "MAIL",
        "FOB",
        "RAIL",
        "SHIP",
        "REG AIR",
        "REG AIR",
        "TRUCK",
        "AIR"
    };
    vectors.emplace_back(make_flat_vector<std::string>(lShipmodeData));
    std::vector<std::string> lCommentData = {
        " the furiously final foxes. quickly final p",
        "thely ironic",
        "ate furiously. even, pending pinto bean",
        "ackages af",
        "odolites. slyl",
        "ng the regular requests sleep above",
        "lets above the slyly ironic theodolites sl",
        "lyly regular excuses affi",
        "lly unusual theodolites grow slyly above",
        " the quickly ironic pains lose car"
    };
    vectors.emplace_back(make_flat_vector<std::string>(lCommentData));

    // Write data into an ORC file.
    writeToFile(
        tmpDir_->getPath() + "/mock_lineitem.orc",
        {make_row_vector(type->names(), vectors)});

    // Find and deserialize Substrait plan json file.
    std::string planPath =
            getDataFilePath("pollux/substrait/tests", "data/q6_first_stage.json");

    // Read q6_first_stage.json and resume the Substrait plan.
    ::substrait::Plan substraitPlan;
    JsonToProtoConverter::readFromFile(planPath, substraitPlan);

    // Convert to Pollux PlanNode.
    kumo::pollux::substrait::SubstraitPolluxPlanConverter planConverter(
        pool_.get());
    auto planNode = planConverter.toPolluxPlan(substraitPlan);

    auto expectedResult = make_row_vector({
        make_flat_vector<double>(1, [](auto /*row*/) { return 13613.1921; }),
    });

    exec::test::AssertQueryBuilder(planNode)
            .splits(makeSplits(planConverter, planNode))
            .assertResults(expectedResult);
}
